package com.shengqin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shengqin.common.pojo.CommonPage;
import com.shengqin.common.pojo.CommonResult;
import com.shengqin.config.CommonException;
import com.shengqin.entity.Role;
import com.shengqin.entity.User;
import com.shengqin.pojo.user.RoleSaveParam;
import com.shengqin.service.IRoleService;
import com.shengqin.service.IUserService;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("admin/v1/role")
public class RoleController {

    @Resource
    private IRoleService roleService;
    @Resource
    private IUserService userService;

    @PostMapping("queryPage")
    public CommonResult<Page<Role>> queryPage(@RequestBody CommonPage<Role> queryPageParam) {
        return CommonResult.data(roleService.queryPage(queryPageParam));
    }

    @PostMapping("queryList")
    public CommonResult<List<Role>> queryList() {
        Object loginId = StpUtil.getLoginId();
        if (loginId != null && !loginId.equals("1")) {
            User user = userService.getById(loginId.toString());
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Role::getOpened, 1)
                    .or().eq(Role::getId, user.getRoleId());
            return CommonResult.data(roleService.list(queryWrapper));
        }
        return CommonResult.data(roleService.list());
    }

    @PostMapping("save")
    public CommonResult<Boolean> save(@RequestBody RoleSaveParam roleSaveParam) {
        return CommonResult.data(roleService.onSave(roleSaveParam));
    }

    @PostMapping("delete")
    public CommonResult<Boolean> delete(@RequestBody RoleSaveParam roleSaveParam) {
        List<User> users = userService.listByRoleId(roleSaveParam.getId());
        if (!CollectionUtils.isEmpty(users)) {
            throw new CommonException("该角色下存在用户，不能删除");
        }
        return CommonResult.data(roleService.removeById(roleSaveParam.getId()));
    }

}
